package com.youdianda.controller;


import com.youdianda.constant.MessageConstant;
import com.youdianda.result.Result;
import com.youdianda.untils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;


    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        log.info("文件上传：{}", file);

        try {
            //获取文件名
            String originalFilename = file.getOriginalFilename();

            //截取文件名后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

            //构造新的文件名
            String newFilename = UUID.randomUUID().toString() + extension;

            //文件请求路径
            String filPath = aliOssUtil.upload(file.getBytes(), newFilename);

            String newFilePath = "/" + filPath;

            //获取文件大小
            long size = file.getSize();
            String s = String.valueOf(size);

            //创建新的map集合
            Map<String,String>map = new HashMap<>();
            map.put("mime",extension);
            map.put("name",originalFilename);
            map.put("savePath",newFilePath);
            map.put("size",s);


            return Result.success(map);
        } catch (IOException e) {
            log.error("文件上传失败: {}", e);
        }

        return Result.error(MessageConstant.UPLOAD_FAILED);

    }
}